package com.esun.gateway.config;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;
import com.esun.gateway.response.RestResponse;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author John.xiao
 * @date 2021/8/26 10:41
 */
@Component
public class CustomerBlockHandler implements WebExceptionHandler {
	public CustomerBlockHandler(List<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {

	}

	@Override
	public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
		RestResponse baseResult = new RestResponse("500", "接口限流了");
		ServerHttpResponse serverHttpResponse = exchange.getResponse();
		serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
		byte[] datas = JSON.toJSONString(baseResult).getBytes(StandardCharsets.UTF_8);
		DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(datas);
		return serverHttpResponse.writeWith(Mono.just(buffer));
	}
}
